package com.mnm.asynctaskmanager.core;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.util.Log;

public final class AsyncTaskManager implements IProgressTracker,
		OnCancelListener {

	// private final OnTaskCompleteListener mTaskCompleteListener;
	private final ProgressDialog m_progressDialog;

	public ProgressDialog getmProgressDialog() {
		return m_progressDialog;
	}

	private Task m_asyncTask;

	public AsyncTaskManager(Context context) {// , OnTaskCompleteListener
												// taskCompleteListener) {
		// Save reference to complete listener (activity)
		// mTaskCompleteListener = taskCompleteListener;
		// Setup progress dialog

		m_progressDialog = new ProgressDialog(context);
		m_progressDialog.setIndeterminate(true);
		m_progressDialog.setCancelable(true);
		m_progressDialog.setOnCancelListener(this);
		m_progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	}

	public void setupTask(Task asyncTask) {
		// Keep task
		m_asyncTask = asyncTask;

		TaskProgress message = asyncTask.getM_progressMessage();

		if (message != null) {
			m_progressDialog.setMessage(message.m_message);
		}

		// Wire task to tracker (this)
		m_asyncTask.setProgressTracker(this);
	}

	public void onProgress(final TaskProgress progress) {
		// Show dialog if it wasn't shown yet or was removed on configuration
		// // (rotation) change
		// // Show current message in progress dialog
		if (!m_progressDialog.isShowing()) {
			m_progressDialog.show();
		}

		m_progressDialog.setProgress(progress.m_progress);
		m_progressDialog.setMessage(progress.m_message);
	}

	public void onCancel(DialogInterface dialog) {
		// Cancel task
		m_asyncTask.cancel(true);
		// Notify activity about completion
		// mTaskCompleteListener.onTaskComplete(mAsyncTask);
		// Reset task
		m_asyncTask = null;
	}

	public void onComplete() {
		// Close progress dialog
		if (m_progressDialog != null) {
			m_progressDialog.dismiss();
		}

		// Notify activity about completion
		// mTaskCompleteListener.onTaskComplete(mAsyncTask);

		// Reset task
		m_asyncTask = null;
	}

	public Object retainTask() {
		// Detach task from tracker (this) before retain
		if (m_asyncTask != null) {
			m_asyncTask.setProgressTracker(null);
		}
		// Retain task
		return m_asyncTask;
	}

	public void handleRetainedTask(Object instance) {
		// Restore retained task and attach it to tracker (this)
		if (instance instanceof Task) {
			setupTask((Task) instance);

		}
	}

	public boolean isWorking() {
		// Track current status
		return m_asyncTask != null;
	}

	public void dismissDialog() {
		if (m_progressDialog != null) {
			m_progressDialog.dismiss();
		}
	}
}